import crypto from 'crypto';
import axios from 'axios';
import FormData from 'form-data';

const url = 'https://api.shumaidata.com/v4/id_card/check';
const appid = 'HqUSgbY5OfApBfjqEPPivqEiRnVbR5sU';
const app_security= 'Y6NcjN2NUraQvZjjIovAQ1kByZBbloJh';

/**
 * 生成签名
 * @param {string} appid - 商户分配的appid
 * @param {number} timestamp - 当前时间毫秒数
 * @param {string} app_security - 商户分配的app_security
 * @returns {string} - 生成的签名
 */
const generateSign = (appid, timestamp, app_security) => {
    // 拼接字符串
    const str = `${appid}&${timestamp}&${app_security}`;
    // 进行MD5加密
    const sign = crypto.createHash('md5').update(str).digest('hex');
    
    return sign;
};

async function postForm(data ,method) {
    const form = new FormData();
    data.appid = appid;
    data.app_security = app_security;
    data.timestamp =  Date.now();
    data.sign = generateSign(data.appid, data.timestamp, data.app_security);
    for (const key in data) {
        form.append(key, data[key]);
    }
    try {
        const res = await axios.post(url, form, {
            headers: form.getHeaders(),
        });
        console.info( ` 数脉API ${method} 请求成功,请求url:${url} 请求报文：${JSON.stringify(data)}  返回报文：${JSON.stringify(res.data)}`);
        return({code:1,data:res.data});
    } catch (error) {
        console.error( ` 数脉API ${method} 请求失败,请求url:${url} 请求报文：${JSON.stringify(data)}  错误原因${error.message}`);
        return({code:0,msg:error.message});
    }
}

async function checkIdCard(name, idcard) {
    return await postForm({name, idcard},'身份证验证');
}
export { checkIdCard };